import logoSrc from "@/assets/dengta.png";
import { encodePath } from "@/utils/utils";
import { getJingWen } from "@/api/jingwen";
import { GEDAN_LIST_TYPE } from "@/utils/constant";
import { baseURL } from "@/utils/request";
import "@leafer-in/export";
import { Leafer, Rect, useCanvas, Image, Text, Platform, Box, Group } from "leafer-ui";
import { Flow } from "@leafer-in/flow";
import { getShiJiItemGepuUrlByIds } from "@/api/cloudbase-sgbedit";
const BGCOLOR = "#6A76AB";

interface IdsInt {
  _id: string;
  type: number;
  dmtUrl?: { gepuUrl: string };
}

interface OptionsInt {
  view: HTMLCanvasElement;
  title: string;
  erCodeString: string;
  id: number;
}

const getErcodeApi = (id: string) => `${baseURL}/start/qrcode?msg=${encodePath(`${id}`)}`;
Platform.image.crossOrigin = "anonymous";
const PADDING = 34;
const MAXWIDTH = 1800;
const cornerRadius = 20;
const LONG_IMG_TYPE = GEDAN_LIST_TYPE;
const BANNER_JPG =
  "https://project-star.oss-cn-beijing.aliyuncs.com/img/calm-sea-on-sunset-with-lighthouse-free-vector.jpg";
/**
 * 加载图片
 * @param {*} data
 * @param {*} x
 * @param {*} y
 * @param {*} width
 * @returns
 */
function loadImage(data: any, x?: number, y?: number, width?: number) {
  const rect = Box.one(
    {
      fill: BGCOLOR,
      children: [
        Rect.one(
          {
            cornerRadius,
            fill: {
              type: "image",
              ...data,
            },
          },
          PADDING,
          void 0,
          MAXWIDTH - PADDING * 2
        ),
      ],
    },
    0,
    0,
    MAXWIDTH
  );

  return rect;
}
/**
 * 绘制二维码
 * @param {*} id
 * @returns
 */
function loadErCodeImage(id: string) {
  return Group.one({
    cornerRadius,
    children: [
      Image.one({ url: getErcodeApi(id) }, 0, void 0, 300, 300),
      Image.one({ url: logoSrc, zIndex: 999 }, 110, 110, 80, 80),
    ],
  });
}

function loadHeader() {
  const HEIGHT = 800;
  return Group.one({
    children: [
      Rect.one(
        {
          fill: {
            type: "image",
            url: BANNER_JPG,
            mode: "clip",
          },
        },
        0,
        0,
        MAXWIDTH,
        HEIGHT
      ),

      Rect.one(
        {
          fill: {
            type: "linear",
            stops: ["#00000000", BGCOLOR],
          },
        },
        0,
        0,
        MAXWIDTH,
        HEIGHT
      ),
    ],
  });
}

class LeaferDraw {
  /**
   * 通过id获取歌谱路径或着经文
   * idsMap.id  唯一的id
   * idsMap.type 1 经文 0 歌谱
   * @param {*} idsMap
   */
  async getContent(idTypes: IdsInt[]) {
    const dmturls = await getShiJiItemGepuUrlByIds(idTypes.map((item) => item._id));

    const idsArr = idTypes.map(async (item) => {
      if (item.type === LONG_IMG_TYPE.song) {
        const url = dmturls.find((ci: any) => ci.id === item._id)?.gepuUrl;
        if (url) {
          return {
            ...item,
            content: url,
          };
        }
        return null;
      } else if (item.type === LONG_IMG_TYPE.jw) {
        const jwRes = (await getJingWen(item._id)) as unknown as any;
        let content = `${item._id}\n`;
        if (jwRes.code === 200) {
          content += jwRes.data
            .map((item: any) => {
              return `${item.jie}.${item.data}`.replaceAll(" ", "");
            })
            .join("\n");
        }
        return {
          ...item,
          content: content,
        };
      }
    });

    return Promise.all(idsArr);
  }
  /**
   * 画图
   * contents 为 getContent的返回参数
   * @param {*} idTypes
   * @param {*} title
   * @returns
   */
  async joinLongImg(idTypes: IdsInt[], options: OptionsInt) {
    const contents = (await this.getContent(idTypes)).filter(Boolean);
    const leafer = new Leafer({
      width: MAXWIDTH,
    });

    const uiEls = [];
    const titleUI = Text.one({
      text: options.title,
      width: MAXWIDTH,
      textAlign: "center",
      fontSize: 86,
      fill: "#FFFFFF",
      fontWeight: 800,
      fontFamily: "Hiragino Sans GB",
    });
    const header = loadHeader();
    uiEls.push(header);
    uiEls.push(titleUI);
    const erCodeUI = loadErCodeImage(options.erCodeString);
    uiEls.push(erCodeUI);
    for (let i = 0; i < contents.length; i++) {
      const item: any = contents[i];
      if (item.type === LONG_IMG_TYPE.song) {
        try {
          const img = await loadImage({ url: item.content }, void 0, void 0, MAXWIDTH);
          uiEls.push(img);
        } catch (error) {
          console.log("获取图片报错：", error);
        }
      } else if (item.type === LONG_IMG_TYPE.jw) {
        const text = Text.one(
          {
            text: item.content,
            textWrap: "break",
            width: MAXWIDTH - PADDING * 2,
            fontSize: 100,
            fill: "#FFFFFF",
            lineHeight: 120,
          },
          void 0,
          void 0,
          MAXWIDTH
        );

        uiEls.push(text);
      }
    }

    const flow = new Flow({
      children: uiEls,
      fill: BGCOLOR,
      width: MAXWIDTH,
      gap: { x: "auto", y: PADDING },
      flow: "y",
      flowAlign: "center",
      padding: [0, 0, PADDING, 0],
    });

    leafer.add(flow);
    const result = await leafer.export("jpg");
    return { base64: result.data, isSplit: false };
  }
}

export default async function joinImage(ids: IdsInt[], options: OptionsInt) {
  const leaferDraw = new LeaferDraw();
  return leaferDraw.joinLongImg(ids, options);
}
